import dayjs from "dayjs"
import { requestSDspotMarketZcq } from "@src/api/fetch"
import { yunNao } from "@src/api/yunNao"
import { getPrivateCommonParams } from "@src/spotMarketPrivateData/data"


/**----------------------------------------发电侧最新额度查询 每一小时一次 start--------------------------------------------- */

// 发电侧最新额度查询 仪表盘数据查询
const getInstrumentPanel = async ({headers, certainDate = ''}:{headers:HeadersInit, certainDate?:string}) => {
  try {
    // 入参中的当前月份
    const currentMonth = certainDate || dayjs().format('YYYY-MM')
    const sendFormData = new URLSearchParams({draw: '1',start: '0',length: '-1'})
    const dataObj = await requestSDspotMarketZcq(
      `https://pmos.sd.sgcc.com.cn:18080/zcq/jysbys/fdczxsbedcx.do?method=getvlddetail&dmonth=${currentMonth}&faids=10047,`,
      sendFormData,
      { method:'POST', headers }
    )
    return Promise.resolve(dataObj)
  } catch(e) {
    console.error(e)
  }
}

// 发电侧上限查询
const getUpperLimitQuery = async ({headers, certainDate = ''}:{headers:HeadersInit,certainDate?:string}) => {
  try {
    // 入参中的当前月份
    const currentMonth = certainDate || dayjs().format('YYYY-MM')
    const dataObj = await requestSDspotMarketZcq(
      `https://pmos.sd.sgcc.com.cn:18080/zcq/jysbys/ydfdcsxyhcx.do?method=getarcdetail&dmonth=${currentMonth}&smonth=${currentMonth}`,
      undefined,
      { method:'POST', headers }
    )
    return Promise.resolve(dataObj?.data?.[0])
  } catch(e) {
    console.error(e)
  }
}

/** 每小时执行一次 */
export const getDeclarationLimitData = async ({headers,unitid, nowStr = '', certainDate = ''}:{headers:HeadersInit,unitid:string, nowStr?:string,certainDate?:string}) => {
   if(!certainDate && !/^.*00$/.test(nowStr)) return
   try{
    Promise.all([getInstrumentPanel({headers, certainDate}), getUpperLimitQuery({headers, certainDate})]).then(async values => {

      const [ getInstrumentPanelData, getUpperLimitQueryData] = values
      const { kmrdl = null, kmchj = null, jhycjdl = null, ljcjdl = null} = getInstrumentPanelData.data?.[0] || {}
      const { dmonth = '', jhydl = null, ljjydl = null } = getUpperLimitQueryData || {}
      const saveDataList = {
        ...getPrivateCommonParams({thirdId:unitid}),
        itemCode: 'medium_trade_declaration_limit',		//山东交易中心id
        targetDate: dmonth?dayjs(dmonth, 'YYYYMM').startOf('month').format('YYYY-MM-DD'):'',  // 交易月份
        // TODO: 可买入和可卖出电量字段不确定是否取得对
        sellableElectricity: kmrdl, // 可卖出电量
        purchasablePower: kmchj,  // 可买入电量
        netContractVolume: jhycjdl, // "净合约成交电量 integer",
        accumulatedTransactionCapacity: ljcjdl, // "累计成交电量 integer",
        netContractLoadLimit:jhydl,  // 净合约电量上限
        totalDealLoadLimit:ljjydl // 累计交易电量上限
      }
      console.log(
        `%c 创建申报额度，小时 :00 时刻执行一次`,
        'background:#35495e ; padding: 1px; border-radius: 3px 0 0 3px;  color: #fff',
      )
      console.log(`存储数据：申报额度 ${dayjs().format('YYYY-MM-DD HH:ss:mm')}`, saveDataList)
      /**如果 targetDate 交易月份为空，那么不调保存接口 */
      if(!saveDataList.targetDate) return
      await yunNao.saveJson(saveDataList)
    });
   }catch(e){
    console.log(
      `%c 创建申报额度，获取数据出错${e}`,
      'background:#35495e ; padding: 1px; border-radius: 3px 0 0 3px;  color: #fff',
    )
   }
}

 
/**----------------------------------------发电侧最新额度查询 end--------------------------------------------- */